package com.example.demo.controller;

import com.example.demo.model.Danmaku;
import com.example.demo.model.User;
import com.example.demo.service.DanmakuService;
import com.example.demo.service.SiteSettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/danmaku-display")
public class DanmakuDisplayController {

    private final DanmakuService danmakuService;
    private final SiteSettingsService siteSettingsService;

    @Autowired
    public DanmakuDisplayController(DanmakuService danmakuService, SiteSettingsService siteSettingsService) {
        this.danmakuService = danmakuService;
        this.siteSettingsService = siteSettingsService;
    }

    @GetMapping
    public String displayPage(Model model, @AuthenticationPrincipal User user) {
        if (user != null) {
            model.addAttribute("user", user);
        }
        
        // 不在这里加载所有弹幕数据，改为通过API动态加载
        model.addAttribute("danmakus", "[]");
        
        // 获取背景图片设置
        String backgroundImage = siteSettingsService.getSettingValue("danmaku.background", "");
        String backgroundOpacity = siteSettingsService.getSettingValue("danmaku.background.opacity", "0.5");
        
        model.addAttribute("backgroundImage", backgroundImage);
        model.addAttribute("backgroundOpacity", backgroundOpacity);
        
        return "danmaku/display";
    }
    
    @GetMapping("/api/data")
    @ResponseBody
    @Cacheable(value = "danmakuData")
    public List<Map<String, Object>> getDanmakuData() {
        // 返回简化版的弹幕数据，避免Hibernate懒加载问题
        List<Danmaku> danmakus = danmakuService.getAllDanmakus();
        
        return danmakus.stream().map(danmaku -> {
            Map<String, Object> item = new HashMap<>();
            item.put("id", danmaku.getId());
            item.put("content", danmaku.getContent());
            item.put("colorType", danmaku.getColorType());
            item.put("createdTime", danmaku.getCreatedTime());
            
            // 简化用户数据
            if (danmaku.getUser() != null) {
                Map<String, Object> user = new HashMap<>();
                user.put("id", danmaku.getUser().getId());
                user.put("username", danmaku.getUser().getUsername());
                // 添加用户头像
                user.put("profileImage", danmaku.getUser().getProfileImage());
                item.put("user", user);
            }
            
            return item;
        }).collect(Collectors.toList());
    }
    
    @PostMapping("/api/send")
    @ResponseBody
    @CacheEvict(value = {"danmakuList", "danmakuData"}, allEntries = true)
    public ResponseEntity<?> sendDanmaku(
            @RequestParam String content,
            @RequestParam(required = false) Integer colorType,
            @AuthenticationPrincipal User user) {
        
        if (content == null || content.trim().isEmpty()) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "弹幕内容不能为空");
            return ResponseEntity.badRequest().body(error);
        }

        if (content.length() > 200) {
            content = content.substring(0, 200);
        }

        if (colorType == null) {
            colorType = (int)(Math.random() * 5) + 1;
        }

        // 创建弹幕对象
        Danmaku danmaku = new Danmaku();
        danmaku.setUser(user);
        danmaku.setContent(content);
        danmaku.setColorType(colorType);
        
        // 为Lambda表达式创建final变量
        final Danmaku finalDanmaku = danmaku;
        
        // 异步保存
        CompletableFuture.runAsync(() -> {
            danmakuService.saveDanmaku(finalDanmaku);
        });
        
        // 立即返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("id", danmaku.getId() != null ? danmaku.getId() : -1);
        result.put("content", content);
        result.put("colorType", colorType);
        result.put("createdTime", danmaku.getCreatedTime());
        
        if (user != null) {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("profileImage", user.getProfileImage());
            result.put("user", userMap);
        }
        
        return ResponseEntity.ok(result);
    }
} 